package com.example.demo.Common;

import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.nio.charset.StandardCharsets;
import java.util.UUID;

public class PasswordTools {
    //加盐加密
    public static  String encrypt(String password){
        String salt= UUID.randomUUID().toString().replace("-","");
        String finalPassword= DigestUtils.md5DigestAsHex((salt+password).getBytes(StandardCharsets.UTF_8));
        String dpPassword=salt+'&'+finalPassword;
        return dpPassword;
    }
    public  static String encrypt(String password,String salt){
        String finalPassword= DigestUtils.md5DigestAsHex((salt+password).getBytes());
        String dpPassword=salt+"&"+finalPassword;
        return dpPassword;
    }
    //验证加盐加密
    public  static boolean decrypt(String password,String dpPassword){
        boolean result=false;
        if(StringUtils.hasLength(password)&&StringUtils.hasLength(dpPassword)
                &&dpPassword.length()==65&&dpPassword.contains("&")){
            //得到盐
            String [] passwordAry=dpPassword.split("\\&");
            String salt=passwordAry[0];
            String finalPassword=encrypt(password,salt);
            if(dpPassword.equals(finalPassword)){
                result=true;
            }
        }
        return result;
    }

    public static void main(String[] args) {
        String password="12345";
        System.out.println(encrypt(password));
    }
}
